package com.quktzhuanka.app.my;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.quktzhuanka.app.R;
import com.quktzhuanka.app.activity.CropActivity;
import com.quktzhuanka.app.base.BaseActivity;
import com.quktzhuanka.app.bean.UserInfoBean;
import com.quktzhuanka.app.common.ACache;
import com.quktzhuanka.app.common.CommonUtils;
import com.quktzhuanka.app.common.LogUtils;
import com.quktzhuanka.app.config.Constants;
import com.quktzhuanka.app.https.HttpUtils;
import com.quktzhuanka.app.utils.BroadcastContants;
import com.quktzhuanka.app.utils.BroadcastManager;
import com.quktzhuanka.app.utils.PickerSelectUtils;
import com.quktzhuanka.app.utils.TypeConvertUtil;
import com.quktzhuanka.app.widget.AutoClearEditText;
import com.quktzhuanka.app.widget.CircleImageView;
import com.quktzhuanka.app.widget.ImageSelectDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

/**
 * 我的资料
 * Created by yohn on 2018/7/14.
 */

public class MyInformationActivity extends BaseActivity {
    @BindView(R.id.bg_head)
    LinearLayout bg_head;
    @BindView(R.id.tv_left)
    TextView tv_left;
    @BindView(R.id.tv_title)
    TextView tv_title;
//    @BindView(R.id.tv_right)
//    TextView tv_right;
    @BindView(R.id.pointtitle)
    TextView pointtitle;

    @BindView(R.id.iv_avater)
    CircleImageView iv_avater;//头像

    @BindView(R.id.et_one)
    AutoClearEditText et_one;//昵称
    @BindView(R.id.et_two)
    AutoClearEditText et_two;//用户名
    @BindView(R.id.et_three)
    AutoClearEditText et_three;//手机号
    @BindView(R.id.et_four)
    AutoClearEditText et_four;//身高
    @BindView(R.id.et_five)
    AutoClearEditText et_five;//体重
    @BindView(R.id.et_six)
    AutoClearEditText et_six;//QQ
    @BindView(R.id.et_seven)
    AutoClearEditText et_seven;//个性签名
    @BindView(R.id.tv_four)
    TextView tv_four;//生日
    @BindView(R.id.tv_address)
    TextView tv_address;//生日
    @BindView(R.id.et_address)
    AutoClearEditText et_adress;//手机号
    @BindView(R.id.rg_sex)
    RadioGroup rg_sex;//生日
    @BindView(R.id.cb_sex_man)
    RadioButton cb_sex_man;//男
    @BindView(R.id.cb_sex_woman)
    RadioButton cb_sex_woman;//女

    private int sexStatus = 1;


    private File avaterFile = null;

    private ACache mAcache;
    String token;

    private UserInfoBean userBean;
    private CityPickerView cityDialog;
    @Override
    protected void initUI() {
        setContentView(R.layout.ac_my_info2);
        ButterKnife.bind(this);
    }

    @Override
    protected void initData() {
        mAcache = ACache.get(this);
        token = mAcache.getAsString(Constants.TOKEN);
        bg_head.setBackgroundColor(getResources().getColor(android.R.color.white));

        //动态设置drawableLeft属性
        Drawable drawable1 = getResources().getDrawable(R.mipmap.icon_back);
        drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
        tv_left.setCompoundDrawables(drawable1, null, null, null);
        tv_left.setVisibility(View.VISIBLE);

        tv_title.setText("个人信息");
//        tv_title.setTextColor(getResources().getColor(R.color.col_333));
//        tv_right.setVisibility(View.VISIBLE);
//        tv_right.setText("编辑");
//        tv_right.setTextColor(getResources().getColor(R.color.red));
        cityDialog = new CityPickerView();
        cityDialog.init(this);
        //使用前配置config，必须，可在application里面全局配置，如果需要设置默认选择城市等，需要特别设置config
        CityConfig cityConfig = new CityConfig.Builder().provinceCyclic(false)
                .cityCyclic(false)
                .districtCyclic(false).build();
        cityDialog.setConfig(cityConfig);
        cityDialog.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                tv_address.setText(province.getName() + "-" + city.getName() + "-" +  district.getName());
            }

            @Override
            public void onCancel() {
            }
        });
        getUserMsg();
        getPointMsg();
    }


    @Override
    protected void initListener() {
        rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.cb_sex_man://男
                        cb_sex_man.isChecked();
                        break;
                    case R.id.cb_sex_woman:// 女
                        cb_sex_woman.isChecked();
                        break;
                }
            }
        });

    }


    @OnClick({ R.id.ll_avater, R.id.tv_left, R.id.tv_four, R.id.tv_finish,R.id.tv_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_finish:
//            case R.id.tv_right:
                editUserMsgRequest();
                break;
            case R.id.ll_avater: //编辑头像
                new ImageSelectDialog(getComeActivity(), R.style.ActionSheetDialogStyle).setOnImageSelectDialogListener(new ImageSelectDialog.onImageSelectDialogListener() {
                    @Override
                    public void onImageSelectResult(String picturePath) {
                        if(picturePath==null||"".equals(picturePath))
                            return;
                        Intent intent = new Intent(getComeActivity(), CropActivity.class);
                        intent.putExtra("url", picturePath);
                        startActivityForResult(intent, 1000);
                    }
                }).show();
                break;
            case R.id.tv_left: //结束
                finish();
                break;
            case R.id.tv_address: //结束
                cityDialog.showCityPicker();
                break;
            case R.id.tv_four: //填写生日
                PickerSelectUtils.getInstence().from(getComeActivity()).TimePicker(tv_four).show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK&&requestCode==1000&&data!=null) {
            avaterFile = new File(data.getStringExtra("url"));
            Glide.with(getComeActivity()).load(data.getStringExtra("url")).into(iv_avater);
            editUserAvatarRequest();
        }
    }

    /**
     * 刷新UI
     **/
    public void refreshUI() {
        if (null != userBean) {
            if (null != userBean.user_detail) {
                et_one.setText(TypeConvertUtil.getString(userBean.user_detail.nickname, ""));//昵称
                et_two.setText(TypeConvertUtil.getString(userBean.user_detail.truename, ""));//用户名
                et_four.setText(TypeConvertUtil.getString(userBean.user_detail.height, ""));//身高
                et_five.setText(TypeConvertUtil.getString(userBean.user_detail.weight, ""));//体重
                et_six.setText(TypeConvertUtil.getString(userBean.user_detail.weixin, ""));//QQ
                et_seven.setText(TypeConvertUtil.getString(userBean.user_detail.signature, ""));//个性签名
                tv_four.setText(TypeConvertUtil.getString(userBean.user_detail.birthday, ""));//生日
                if ("2".equals(userBean.user_detail.sex)) {
                    cb_sex_woman.setChecked(true);
                } else {
                    cb_sex_man.setChecked(true);
                }
                et_adress.setText(TypeConvertUtil.getString(userBean.user_detail.detail_address, ""));//昵称
                if(!"".equals(TypeConvertUtil.getString(userBean.user_detail.province, ""))){
                    tv_address.setText(TypeConvertUtil.getString(userBean.user_detail.province, "")+"-"+TypeConvertUtil.getString(userBean.user_detail.city, "")+"-"+TypeConvertUtil.getString(userBean.user_detail.county, ""));//昵称
                }
            }
            if (null != userBean.user_msg) {
                et_three.setText(TypeConvertUtil.getString(userBean.user_msg.phone, ""));//手机号
            }

            if (!TextUtils.isEmpty(userBean.user_detail.avatar)) {
                Glide.with(this).load(userBean.user_detail.avatar).placeholder(R.mipmap.icon_defult_boy).error(R.mipmap.icon_defult_boy).into(iv_avater);
            }
        }
    }

    /**
     * 获取用户信息
     */
    private void getUserMsg() {
        if (!CommonUtils.isNetworkAvailable()) {
            showToast(getResources().getString(R.string.error_network));
            return;
        }
        RequestParams params = new RequestParams();
        params.put("token", token);
        HttpUtils.post(Constants.GET_USER_MSG, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // 输出错误信息
                LogUtils.e(TAG, "onFailure()--" + responseString);
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                LogUtils.e(TAG, "onSuccess()--" + responseString);
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    //返回码
                    int code = jsonObject.optInt("code");
                    //返回码说明
                    String msg = jsonObject.optString("msg");
                    String data = jsonObject.optString("data");
                    if (0 == code) {
                        if (!TextUtils.isEmpty(data)) {//GSON对数字都当做double解析
                            Gson gson = new Gson();
                            userBean = gson.fromJson(data.trim(), UserInfoBean.class);
                            Glide.with(MyInformationActivity.this).load(userBean.user_detail.avatar).placeholder(R.mipmap.icon_defult_boy).error(R.mipmap.icon_defult_boy).into(iv_avater);
                        }
                        refreshUI();
                    } else {
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                // 显示进度条
                super.onStart();
                showLoadingDialog();
            }
        });

    }

    /**
     * 获取完善信息奖励
     */
    private void getPointMsg() {
        if (!CommonUtils.isNetworkAvailable()) {
            showToast(getResources().getString(R.string.error_network));
            return;
        }
        RequestParams params = new RequestParams();
        params.put("token", token);
        HttpUtils.post(Constants.GET_USER_POINT, params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // 输出错误信息
                LogUtils.e(TAG, "onFailure()--" + responseString);
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                LogUtils.e(TAG, "onSuccess()--" + responseString);
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    //返回码
                    int code = jsonObject.optInt("code");
                    //返回码说明
                    String msg = jsonObject.optString("msg");
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (0 == code) {
                        String typename = data.getString("typename");
                        String num = data.getString("num");
                        pointtitle.setText("完善资料可得"+num+typename);
                    } else {
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                // 显示进度条
                super.onStart();
                showLoadingDialog();
            }
        });

    }

    /**
     * @属性:上传头像
     * @开发者:田哥哥
     * @时间:2018/7/23 20:23
     */
    private void editUserAvatarRequest() {
        try {
            RequestParams requestParams = new RequestParams();
            requestParams.put("user_avatar", avaterFile);
            HttpUtils.postUpload(Constants.EDIT_USER_AVATAR, requestParams, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

                }

                @Override
                public void onStart() {
                    super.onStart();
                    showLoadingDialog();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    closeLoadingDialog();
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseString) {
                    try {
                        JSONObject jsonObject = new JSONObject(responseString);
                        int code = jsonObject.optInt("code");
                        String msg = jsonObject.optString("msg");
                        if (code == 0) {
                            showToast(msg);
                            //更新用户信息
                            BroadcastManager.getInstance(getComeActivity()).sendBroadcast(BroadcastContants.sendUserMessage);
                        } else {
                            showToast(msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
        } catch (Exception e) {
//                Toast.makeText(this, "上传失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    }

    public static String byteArrayToStr(byte[] byteArray) {
        if (byteArray == null) {
            return null;
        }
        String str = new String(byteArray);
        return str;
    }

    private void editUserMsgRequest() {
        if (TextUtils.isEmpty(getTextEditValue(et_one))) {
            showToast("请填写用户昵称");
            return;
        }
        RequestParams requestParams = new RequestParams();
        requestParams.put("token", token);
        requestParams.put("nickname", getTextEditValue(et_one)); //用户名称
        requestParams.put("truename", getTextEditValue(et_two)); //真实姓名
        requestParams.put("height", getTextEditValue(et_four)); //身高
        requestParams.put("weight", getTextEditValue(et_five)); //体重
//        requestParams.put("blood", getTextEditValue(et_one)); //血型 1A型 2B型 3AB型 4O型 5其它
        requestParams.put("birthday", getTextEditValue(tv_four)); //出生日期
        requestParams.put("weixin", getTextEditValue(et_six)); //微信号
//        requestParams.put("weixin", getTextEditValue(et_one)); //微信号
        if(!"".equals(tv_address.getText().toString())){
            requestParams.put("province",tv_address.getText().toString().split("-")[0]); //省份
            requestParams.put("city", tv_address.getText().toString().split("-")[1]); //城市
            requestParams.put("county", tv_address.getText().toString().split("-")[2]); //县/区域
        }
        requestParams.put("detail_address", et_adress.getText().toString()); //详细地址
        requestParams.put("signature", getTextEditValue(et_seven)); //个性签名
        //性别 1男 2女 3保密
        if (cb_sex_man.isChecked()) {
            requestParams.put("sex", "1");
        } else if (cb_sex_woman.isChecked()) {
            requestParams.put("sex", "2");
        } else {
            requestParams.put("sex", "3");
        }

        HttpUtils.post(Constants.EDIT_USER_MSG, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
                LogUtils.e(TAG, "--" + responseString);
            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    int code = jsonObject.optInt("code");
                    String msg = jsonObject.optString("msg");
                    if (code == 0) {
                        showToast(msg);
                        //更新用户信息
                        BroadcastManager.getInstance(getComeActivity()).sendBroadcast(BroadcastContants.sendUserMessage);
                        finish();
                    } else {
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
